//
//  AccountSettingViewController.m
//  TTAddressBook
//
//  Created by WangJuan on 12-1-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AccountSettingViewController.h"
#import "CommTools.h"
#import "imagePath.h"
#import "SettingConstants.h"
#import "SettingViewController.h"

@implementation AccountSettingViewController
@synthesize pictureButton;
@synthesize nameField;
@synthesize accountLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) 
    {
        self.title = @"帐号设置";
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
                                     initWithTitle:@"取消"
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(cancelClick)];
    self.navigationItem.leftBarButtonItem = cancelButton;
    [cancelButton release];
	
    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"保存"
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(saveClick)];
    self.navigationItem.rightBarButtonItem = saveButton;
    [saveButton release];
    
//    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0)
//    {
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:UIContacts_contacts_navigationBar] forBarMetrics:0];
//        
//        [cancelButton setBackgroundImage:[UIImage imageNamed:kNavigationBarButtonPng] forState:UIControlStateNormal barMetrics:0];
//        [cancelButton setBackgroundImage:[UIImage imageNamed:kNavigationBarButtonOnPng] forState:UIControlStateSelected barMetrics:0];
//        
//        [saveButton setBackgroundImage:[UIImage imageNamed:kNavigationBarButtonPng] forState:UIControlStateNormal barMetrics:0];
//        [saveButton setBackgroundImage:[UIImage imageNamed:kNavigationBarButtonOnPng] forState:UIControlStateSelected barMetrics:0];
//    }
//    else
//    {
//        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255 green:130.0/255 blue:180.0/255 alpha:0.8];
//    }
    
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    backgroundView.image = [UIImage imageNamed:kSettingBackGroundPng];
    [self.view addSubview:backgroundView];
    [self.view sendSubviewToBack:backgroundView];
    [backgroundView release];

}

- (void)viewDidUnload
{
    [self setNameField:nil];
    [self setPictureButton:nil];
    [self setAccountLabel:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)backgroudClick:(id)sender 
{
    [nameField resignFirstResponder];
}

- (IBAction)changeAccount:(id)sender 
{
    [nameField resignFirstResponder];
    
    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: @"更换帐号将重新以当前的手机号建立新帐号，并将在此手机上删除老帐号数据"
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:@"确定"
                           otherButtonTitles: nil];
    
    menu.tag = ChangeAccountActionSheetTag;
    [menu showInView:self.view.window];
    [menu release];
}

- (IBAction)accoutButtonClick:(id)sender 
{
    [nameField resignFirstResponder];
}

- (IBAction)pictureButtonClick:(id)sender 
{
    [nameField resignFirstResponder];
    
    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: @"编辑照片"
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:nil
                           otherButtonTitles: @"相册图片", @"拍照", nil];
    
    menu.tag = ChangePicActionSheetTag;
    [menu showInView:self.view.window];
    [menu release];
}

- (IBAction)textFieldDoneEditing:(id)sender 
{
    [sender resignFirstResponder];
}

- (void)cancelClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveClick
{
    if ( picture != nil )
    {
        //将图片存到应用程序的document目录下
        NSString *path = [self findUniqueSavePath];
        [UIImagePNGRepresentation(picture) writeToFile: path atomically:YES];
        
        //[self.modelEngine setUserImagePath: path];
    }
    
   // [self.modelEngine setUserName: nameField.text];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc 
{
    [nameField release];
    [pictureButton release];
    [accountLabel release];
    [super dealloc];
}

#pragma mark UIActionSheetDelegate

#pragma mark ImagePicker

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; 
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    if ( !error )
    {
        [alert setMessage:@"Image written to photo album"];
    }
	else
    {
        NSString *msg = [[NSString alloc] initWithFormat:@"Error writing to photo album: %@", [error localizedDescription]];
		[alert setMessage: msg];
        [msg release];
    }
    
    [alert show];
    [alert release];
}

- (NSString *) findUniqueSavePath
{
	int i = 1;
	NSString *path; 
    
	do 
    {
		// iterate until a name does not match an existing file
	    path = [NSString stringWithFormat:@"%@/Documents/IMAGE_%04d.PNG", NSHomeDirectory(), i++];
	} while ([[NSFileManager defaultManager] fileExistsAtPath:path]);
	
	return path;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    picture = [info objectForKey:@"UIImagePickerControllerOriginalImage"] ;
    [pictureButton setBackgroundImage:picture forState:UIControlStateNormal];
    
    //Save the image to the album
    if ( isSavedToAlbum )
    {
        UIImageWriteToSavedPhotosAlbum( picture, self, @selector(image:didFinishSavingWithError:contextInfo:), nil );
    }
    
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch ( alertView.tag )
    {
        default:
            break;
    }
}

@end
